package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pojo.Book;
import pojo.Order;
import pojo.User;
import service.BookManager;
import service.OrderManager;
import service.factory.ManagerFactory;

/**
 * Servlet implementation class CommitOrder
 */
@WebServlet("/commitOrder")
public class CommitOrder extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private OrderManager manager;
	private BookManager bookManager;
	
    public CommitOrder() {
        super();
        manager = ManagerFactory.getOrderManagerInstance();
        bookManager = ManagerFactory.getBookManagerInstance();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Map<Book,Integer> cart = (Map<Book, Integer>) session.getAttribute("cart");
		User user = (User) session.getAttribute("user");
		if (cart==null||cart.isEmpty()) {
			request.setAttribute("info", "you have no books to buy");
			request.getRequestDispatcher("order.jsp").forward(request, response);
		}else{
			List<Order> orders = new ArrayList<>();
			synchronized (cart) {
				Date date = new Date();
				for (Book book : cart.keySet()) {
					Order order = new Order();
					order.setB_id(book.getId());
					order.setU_id(user.getId());
					order.setCount(cart.get(book));
					order.setOrderTime(date);
					orders.add(order);
				}
				cart.clear();
			}
			int m = manager.order(orders);
			if (m>0) {
				request.getRequestDispatcher("order").forward(request, response);
			}else{
				request.setAttribute("info", "error");
				request.getRequestDispatcher("order.jsp").forward(request, response);
			}
			
		}
	}

}
